<?php


namespace XinYaTable\Forms\Models;


class EloquentFormField extends BaseModel {
    protected $table = 'sys_form_fields';
    
    protected $appends = [
        'options'
    ];
    
    protected $casts = [
        'props'    => 'json',
        'validate' => 'json',
        'style'    => 'json'
    ];
    
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function fieldOptions() {
        return $this->hasMany(EloquentFormFieldOption::class, 'field_id', 'id')
            ->select(['field_id', 'title', 'value', 'order'])
            ->orderBy('order');
    }
    
    /**
     * @return mixed
     */
    public function getOptionsAttribute() {
        switch ($this->field_name) {
            default:
                $fieldOptions = $this->fieldOptions->toArray();
        }
        
        return $this->_convertOptionValueToString($fieldOptions);
    }
    
    /**
     * 将option的value值转为字符串，因为前端强类型对比，防止每次要转换的麻烦或者忘记转换
     *
     * @param $fieldOptions
     *
     * @return array
     */
    private function _convertOptionValueToString($fieldOptions) {
        foreach ($fieldOptions as $optionIndex => $fieldInfo) {
            $fieldOptions[$optionIndex]['value'] = (string)$fieldInfo['value'];
            if (isset($fieldInfo['parent_option_value'])) {
                $fieldOptions[$optionIndex]['parent_option_value'] = (string)$fieldInfo['parent_option_value'];
            }
        }
        
        return $fieldOptions;
    }
}